#include "file_utils.hpp"

std::string file_get_content(const std::string &path) {
    std::ifstream file(path, std::ios::binary);
    if (!file.is_open()){
        return {};
    }
    std::string content{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
    return content;
}


std::pair<std::string, long> file_get_content_bytes(const std::string &path, int start, int end){
    // start和end：开始字节和结束字节，都是闭区间
    if (start < 0) return {};
    std::ifstream file(path, std::ios::in | std::ios::binary);
    if (!file.is_open()) {
        return {};
    }
    file.seekg(0, file.end);
    int length = (int)file.tellg();
    if (start > length) return {};

    if (end == -1) {
        end = length-1;
    }
    else if (end < start){
        return {};
    } 
    else {
        end = std::min(end, length-1);
    }
    
    file.seekg(start, file.beg);
    std::string content(end-start+1, '\0');
    file.read(&content[0], end-start+1);
    return {content, length};
}

int file_length(const std::string &path) {
    std::ifstream file(path, std::ios::in | std::ios::binary);
    if (!file.is_open()) {
        return -1;
    }
    file.seekg(0, file.end);
    int length = (int)file.tellg();
    return length;
}


